package com.lottery.im.module.chat.ui;

import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.GiveRedPackets;
import com.lottery.im.base.BaseActivity;
import com.lottery.im.constant.Constants;
import com.lottery.im.module.chat.presenter.SendSingleRedPacketsPresenter;
import com.lottery.im.module.chat.view.SendSingleRedPacketsView;
import com.lottery.im.module.tim.model.GroupInfo;
import com.lottery.im.util.StatusBarHelper;
import com.lottery.im.widget.dialog.ConfirmWarnDialogBuilder;
import com.lottery.im.widget.dialog.PassValidationDialogBuilder;
import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * 发送群聊红包
 */
public class SendGroupRedPacketsActivity extends BaseActivity<SendSingleRedPacketsPresenter>
    implements SendSingleRedPacketsView {

  public final static String ID_KEY = "ID_KEY";

  public static void create(Activity activity, String id, int requestCode) {
    Intent intent = new Intent(activity, SendGroupRedPacketsActivity.class);
    intent.putExtra(ID_KEY, id);
    activity.startActivityForResult(intent, requestCode);
  }

  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;
  @BindView(R.id.tv_title1) TextView mTvTitle1;
  @BindView(R.id.et_money) EditText mEtMoney;
  @BindView(R.id.tv_tip1) TextView mTvTip1;
  @BindView(R.id.et_num) EditText mEtNum;
  @BindView(R.id.tv_tip2) TextView mTvTip2;
  @BindView(R.id.et_note) EditText mEtNote;
  @BindView(R.id.tv_all_money) TextView mTvAllMoney;
  @BindView(R.id.layout_content) RelativeLayout mLayoutContent;
  @BindView(R.id.tv_error_tip) TextView mTvErrorTip;

  private String groupId;

  private String[] mTabNames = { "普通红包", "手气红包" };

  @Override protected int getLayoutResId() {
    return R.layout.activity_send_groupleredpackets;
  }

  @Override protected void initPresenter() {
    presenter = new SendSingleRedPacketsPresenter(this, this, this);
    presenter.init();
  }

  @Override public void initView() {
    StatusBarHelper.translucent(this);
    groupId = getIntent().getStringExtra(ID_KEY);

    initTabs();
    mTvTip2.setText("本群共" + GroupInfo.getInstance()
        .getGroupProfile(GroupInfo.publicGroup, groupId)
        .getMemberNum() + "人");
  }

  @OnClick({ R.id.iv_back, R.id.btn_confirm, R.id.tv_record })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        finish();
        break;
      case R.id.btn_confirm:
        submit();
        break;
      case R.id.tv_record:
        NewFragmentActivity.create(this, NewFragmentActivity.FragmentInfoType.RedPacketsRecord);
        break;
    }
  }

  @OnTextChanged(value = R.id.et_money, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
  void afterMoneyTextChanged(Editable content) {

    String temp = content.toString();
    int posDot = temp.indexOf(".");
    if (posDot > 0 && temp.length() - posDot - 1 > 2) {
      content.delete(posDot + 3, posDot + 4);
    }

    if (TextUtils.isEmpty(content.toString())) {
      mTvAllMoney.setText("0.00");
      return;
    }
    DecimalFormat df = new DecimalFormat("#0.00");
    try {
      double moneyDouble = Double.valueOf(content.toString());
      if (mTabLayout.getCurrentTab() == 1) {
        mTvAllMoney.setText(df.format(moneyDouble));

        int num = Integer.valueOf(mEtNum.getText().toString());

        if (moneyDouble / num < 0.01 || moneyDouble / num > 200) {
          mTvErrorTip.setVisibility(View.VISIBLE);
        } else {
          mTvErrorTip.setVisibility(View.GONE);
        }
      } else {
        if (moneyDouble < 0.01 || moneyDouble > 200) {
          mTvErrorTip.setVisibility(View.VISIBLE);
        } else {
          mTvErrorTip.setVisibility(View.GONE);
        }

        int num = Integer.valueOf(mEtNum.getText().toString());
        mTvAllMoney.setText(df.format(moneyDouble * num));
      }
    } catch (Exception e) {
    }
  }

  @OnTextChanged(value = R.id.et_num, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
  void afterNumTextChanged(Editable content) {

    if (mTabLayout.getCurrentTab() == 1) {
      try {
        double moneyDouble = Double.valueOf(mEtMoney.toString());
        int num = Integer.valueOf(content.toString());
        if (moneyDouble / num < 0.01 || moneyDouble / num > 200) {
          mTvErrorTip.setVisibility(View.VISIBLE);
        } else {
          mTvErrorTip.setVisibility(View.GONE);
        }
      } catch (Exception e) {

      }

      return;
    }

    if (TextUtils.isEmpty(content.toString())) {
      mTvAllMoney.setText("0.00");
      return;
    }

    String money = mEtMoney.getText().toString();
    if (TextUtils.isEmpty(money)) {
      return;
    }
    try {
      double moneyDouble = Double.valueOf(money);
      int num = Integer.valueOf(content.toString());
      DecimalFormat df = new DecimalFormat("#0.00");
      mTvAllMoney.setText(df.format(moneyDouble * num));
    } catch (Exception e) {
    }
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {

        mEtMoney.setText("");
        mEtNum.setText("");
        mTvAllMoney.setText("0.00");
        if (position == 0) {
          mTvTitle1.setText("单个金额");
          mTvTip1.setText("发送普通红包群里每个人收到固定金额");
        } else {
          mTvTitle1.setText("总金额");
          mTvTip1.setText("发送手气红包群里每个人收到随机金额");
        }
      }

      @Override public void onTabReselect(int position) {

      }
    });
  }

  private void submit() {

    String money = mEtMoney.getText().toString();
    if (TextUtils.isEmpty(money)) {
      showToast("请输入金额");
      return;
    }
    String num = mEtNum.getText().toString();
    if (TextUtils.isEmpty(num)) {
      showToast("请输入红包个数");
      return;
    }
    String note = mEtNote.getText().toString();
    if (!MyApplication.getInstance().getUserInfo().getIsSetPayPwd().equals("Y")) {
      ConfirmWarnDialogBuilder.getInstance(this).setContent("请先设置资金密码")
          .setCancel("取消", null)
          .setConfirm("去设置", v -> NewFragmentActivity.create(mActivity,
              NewFragmentActivity.FragmentInfoType.SETMONEYPWD)).show();
      return;
    }
    hideKeyBoard();

    PassValidationDialogBuilder.getInstance(mActivity).setCallBack(
        code -> {

          if (mTabLayout.getCurrentTab() == 0) {
            presenter.giveRedPackets(groupId, 0,
                mTvAllMoney.getText().toString(), money, num, note, code);
          } else {
            presenter.giveRedPackets(groupId, 1,
                mTvAllMoney.getText().toString(), null, num, note, code);
          }
        }).show();
  }

  @Override public void giveSuc(GiveRedPackets redPackets) {
    Intent data = new Intent();
    String note = mEtNote.getText().toString();
    if (TextUtils.isEmpty(note)) {
      data.putExtra(ID_KEY,
          redPackets.getRedPacketsId() + Constants.HONGBAO_INFO + "恭喜发财，大吉大利");
    } else {
      data.putExtra(ID_KEY,
          redPackets.getRedPacketsId() + Constants.HONGBAO_INFO + mEtNote.getText().toString());
    }
    setResult(Activity.RESULT_OK, data);
    finish();
  }
}
